package com.lytoyo.neihanduanzi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lytoyo.neihanduanzi.aspect.Login;
import com.lytoyo.neihanduanzi.mapper.UserAttentionMapper;
import com.lytoyo.neihanduanzi.model.Result;
import com.lytoyo.neihanduanzi.model.dto.UserInfoDto;
import com.lytoyo.neihanduanzi.model.user.UserAttention;
import com.lytoyo.neihanduanzi.model.user.UserInfo;
import com.lytoyo.neihanduanzi.service.UserAttentionService;
import com.lytoyo.neihanduanzi.service.UserService;
import com.lytoyo.neihanduanzi.utils.AuthContextHolder;
import com.lytoyo.neihanduanzi.utils.Constant;
import com.lytoyo.neihanduanzi.utils.MD5Utils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Package:com.lytoyo.neihanduanzi.controller
 *
 * @ClassName:UserController
 * @Create:2025/1/9 19:29
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RabbitAdmin rabbitAdmin;

    @Resource
    private DirectExchange directExchange;

    private static final String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserAttentionMapper userAttentionMapper;

    /**
     * 获取验证码
     * @param email
     * @return
     */
    @GetMapping("/requestVerCode")
    public Result requestCode(@RequestParam("email") String email) {
        log.info("email:{}",email);
        //检查邮箱格式
        if (!email.matches(em)) {
            return Result.fail(-1, "邮箱格式不正确");
        }
        userService.getVerCode(email);
        return Result.success("");
    }

    /**
     * 注册
     * @param userInfo
     * @return
     */
    @PostMapping("/regist")
    public Result regist(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        String code = request.getHeader("code");
        return userService.regist(userInfo,code);
    }

    /**
     * 登录
     * @param userInfo
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        userInfo.setPassword(MD5Utils.code(userInfo.getPassword()));
        UserInfo user = userService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getEmail, userInfo.getEmail()).eq(UserInfo::getPassword, userInfo.getPassword()));
        if(null == user) return Result.fail(-1,"账号或密码错误");
        UserInfoDto userInfoDto = new UserInfoDto();
        BeanUtils.copyProperties(user,userInfoDto);
        //存入内存
        redisTemplate.opsForValue().set(Constant.USER_LOGIN_KEY+userInfoDto.getId(),user,Constant.USER_LOGIN_TTL, TimeUnit.MINUTES);
        // 动态创建用户专属队列
        Queue queue = new Queue("user." + userInfoDto.getId() + ".queue", true, false, false);
        rabbitAdmin.declareQueue(queue); // 声明队列

        // 绑定队列到交换机，路由键为用户ID
        Binding binding = BindingBuilder.bind(queue)
                .to(directExchange)
                .with(userInfoDto.getId().toString());//路由键=用户ID
        rabbitAdmin.declareBinding(binding);
        return Result.success(userInfoDto);
    }

    /**
     * 获取用户的点赞、关注、粉丝数量
     * @return
     */
    @Login
    @GetMapping("/request/status")
    public Result reqStatus(){
        Long userId = AuthContextHolder.getUserId();
        Map<String, Object> map = userService.requestStatus(userId);
        //查询关注用户的id列表
        List<UserAttention> userAttentionList = userAttentionMapper.selectList(new QueryWrapper<UserAttention>().eq("fan", userId).select("user_id"));
        List<Long> list = userAttentionList.stream().map(UserAttention::getUserId).collect(Collectors.toList());
        map.put("attentionList",list);

        return Result.success(map);
    }

    /**
     * 获取目标用户的详细信息
     * @param userId
     * @return
     */
    @GetMapping("/other/imfor")
    public Result otherImfor(@RequestParam("userId")Long userId){
        return this.userService.otherImfor(userId);
    }


}
